package ee.ttu.lecturerate;

import java.util.Date;

import ee.ttu.lecturerate.data.Comment;
import ee.ttu.lecturerate.data.User;
import ee.ttu.lecturerate.http.RequestAssembler;
import ee.ttu.lecturerate.http.RequestAsyncTask;
import ee.ttu.lecturerate.http.RequestInput;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;

public class RateActivity extends Activity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rate);
		
		Button rateButton = (Button) findViewById(R.id.rateButton);
		rateButton.setOnClickListener(new RateButtonOnClickListener());
		
		Button cancelButton = (Button) findViewById(R.id.cancelButton);
		cancelButton.setOnClickListener(new CancelButtonOnClickListener());
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.rate, menu);
		return true;
	}
	
	class RateButtonOnClickListener implements View.OnClickListener {
		@Override
		public void onClick(View arg0) {
			
			Log.d("RateActivity.RateButtonOnClickListener.onClick()", "Event occured");
			
			String lectureId = getIntent().getStringExtra("lectureId");
			
			LectureRate application = (LectureRate) getApplication();
			User user = application.getActiveUser();
			
			if(lectureId != null && user != null)
			{
				RatingBar ratingBar = (RatingBar) findViewById(R.id.rateRatingBar);
				int rating = Math.round(ratingBar.getRating());
				
				TextView commentTextView = (TextView) findViewById(R.id.rateComment);
				String commentText = commentTextView.getText().toString();
				
				Comment comment = new Comment();
				comment.setAuthor(user.getUsername());
				comment.setDate(new Date(System.currentTimeMillis())); // Server will override this
				comment.setRating(rating);
				comment.setComment(commentText);
				
				RequestInput input = RequestAssembler.assemblePutComment(comment, lectureId);
				RequestAsyncTask task = new RequestAsyncTask(RateActivity.this);
				task.execute(input);
			}
		}
		
	}
	
	class CancelButtonOnClickListener implements View.OnClickListener {
		@Override
		public void onClick(View arg0) {
			RateActivity.this.finish();
		}
		
	}

}
